
#include "lxccreatedialog.h"
#include "lxcutils.h"
#include "mainwindow.h"
#include "spkbutton.h"
#include "ui_mainwindow.h"

#include <QMessageBox>

SpkButton *button;
MainWindow::MainWindow(QWidget *parent) : QMainWindow(parent)
  , ui(new Ui::MainWindow)
{
    ui->setupUi(this);

    connect(ui->lxc_containers, &QListWidget::itemClicked, this, &MainWindow::slotContainersItemClicked);

    m_menu_containers.addAction(ui->actionCreate);
    m_menu_containers.addAction(ui->actionDestroy);
    ui->lxc_containers->setContextMenuPolicy(Qt::CustomContextMenu);

    on_btn_refresh_clicked();

    button = new SpkButton(":/youhua.png", ":/youhua_Hover.png", ":/youhua_Leave.png", this);

    button->show();
}

MainWindow::~MainWindow()
{
	
}

void MainWindow::on_btn_refresh_clicked()
{
    ui->c_start->setEnabled(false);
    ui->c_stop->setEnabled(false);

    ui->lxc_containers->clear();
    ui->lxc_containers->addItems(LXCUtils::GetLXCContainers());

    if (ui->lxc_containers->count() > 0) {
        ui->c_start->setEnabled(true);
        ui->c_stop->setEnabled(true);


        ui->lxc_containers->setCurrentRow(0);
        slotContainersItemClicked(ui->lxc_containers->currentItem());
    }
}

void MainWindow::slotContainersItemClicked(QListWidgetItem *item)
{
    QString info = LXCProcess::lxc_info(item->text()).getStdout();

    ui->c_start->setEnabled(info.contains("STOPPED"));
    ui->c_stop->setEnabled(!info.contains("STOPPED"));

    ui->lxc_info->setText(info);
}

void MainWindow::resizeEvent(QResizeEvent *event)
{
    button->setGeometry(width()-95,0,95,95);
    QMainWindow::resizeEvent(event);
}

void MainWindow::on_lxc_containers_customContextMenuRequested(const QPoint &pos)
{
    m_menu_containers.exec(mapToGlobal(pos));
}

void MainWindow::on_actionCreate_triggered()
{
    LxcCreateDialog dialog;
    dialog.exec();
}

void MainWindow::on_actionDestroy_triggered()
{
    QString container = ui->lxc_containers->currentItem()->text();
    auto button = QMessageBox::question(this, "确认删除?", QString("是否确认删除'%1'容器?").arg(container));
    if (button & QMessageBox::Yes) {
        LXCProcess::lxc_destroy(container);
        on_btn_refresh_clicked();
    }
}

void MainWindow::on_c_start_clicked()
{
    QString container = ui->lxc_containers->currentItem()->text();
    ui->lxc_info->setText(LXCProcess::lxc_start(container).getFull());
}

void MainWindow::on_c_stop_clicked()
{
    QString container = ui->lxc_containers->currentItem()->text();
    ui->lxc_info->setText(LXCProcess::lxc_stop(container).getFull());
}

